package com.row.common.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.row.common.config.YmlConfig;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Hashtable;

/**
 * @ClassName QRcodeUtils
 * @Description 二维码工具类
 * @Author Row
 * @Date 2019/6/12 11:32
 **/
public class QRcodeUtils {

    /**
     * 生成二维码图片
     * @param codeInfo 二维码内容
     * @param fileName 二维码文件名
     * @throws IOException
     */
    public static void createQRcode(String fileName,String codeInfo)  {
        //String text="www.baidu.com";
        int width=100;
        int height=100;
        String format="png";
        Hashtable hints=new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix=new MultiFormatWriter().encode(codeInfo, BarcodeFormat.QR_CODE, width, height,hints);
            Path file=new File(YmlConfig.getFilePath()+YmlConfig.getQRcodePath()+fileName+"."+format).toPath();//在根目录的二维码文件夹生成二维码图片
            try {
                MatrixToImageWriter.writeToPath(bitMatrix, format, file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     *  解析二维码
     * @param url 二维码地址
     * @throws NotFoundException
     */
    public static void analysisQRcode(String url){
        MultiFormatReader formatReader=new MultiFormatReader();
        File file =new File(url);
        BufferedImage image=null;
        try {
            image = ImageIO.read(file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BinaryBitmap binaryBitmap =new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Hashtable hints=new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            Result result=formatReader.decode(binaryBitmap,hints);
            System.err.println("解析结果1："+result.toString());
            System.out.println("解析结果2："+result.getBarcodeFormat());
            System.out.println("解析结果3："+result.getText());
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建二维码
     * @param contents
     * @param width
     * @param height
     * @param response
     */
    public static void createQRCode(String contents, int width, int height,HttpServletResponse response) {
        Hashtable hints = new Hashtable();

        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //容错级别最高
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  //设置字符编码
        hints.put(EncodeHintType.MARGIN, 1);                //二维码空白区域,最小为0也有白边,只是很小,最小是6像素左右
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints); // 1、读取文件转换为字节数组
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedImage image = toBufferedImage(bitMatrix);
            //转换成png格式的IO流
            ImageIO.write(image, "png", response.getOutputStream());
//            byte[] bytes = out.toByteArray();
//            // 2、将字节数组转为二进制
//            BASE64Encoder encoder = new BASE64Encoder();
//            binary = encoder.encodeBuffer(bytes).trim();
        } catch (WriterException e) { // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }




    /**
     * image流数据处理
     *
     * @author ianly
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
}
